package com.example.gulimallproduct.service.impl;

import cn.hutool.core.collection.CollectionUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.example.common.to.SkuReductionTO;
import com.example.common.to.SpuBoundTO;
import com.example.common.utils.R;
import com.example.gulimallproduct.entity.*;
import com.example.gulimallproduct.feigen.CouponFeignClient;
import com.example.gulimallproduct.request.SelectSpuOrSkuInfoPageRequest;
import com.example.gulimallproduct.service.*;
import com.example.gulimallproduct.vo.*;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.math.BigDecimal;
import java.time.LocalDateTime;
import java.util.*;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.example.common.utils.PageUtils;
import com.example.common.utils.Query;

import com.example.gulimallproduct.dao.SpuInfoDao;
import org.springframework.transaction.annotation.Transactional;


@Service("spuInfoService")
public class SpuInfoServiceImpl extends ServiceImpl<SpuInfoDao, SpuInfoEntity> implements SpuInfoService {
    @Autowired
    private SpuInfoDescService spuInfoDescService;
    @Autowired
    private SpuImagesService spuImagesService;
    @Autowired
    private ProductAttrValueService productAttrValueService;
    @Autowired
    private AttrService attrService;
    @Autowired
    private SkuInfoService skuInfoService;
    @Autowired
    private SkuImagesService skuImagesService;
    @Autowired
    private SkuSaleAttrValueService skuSaleAttrValueService;
    @Autowired
    private CouponFeignClient couponFeignClient;
    @Override
    public PageUtils queryPage(Map<String, Object> params) {
        IPage<SpuInfoEntity> page = this.page(
                new Query<SpuInfoEntity>().getPage(params),
                new QueryWrapper<>()
        );

        return new PageUtils(page);
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public R saveSpuInfo(SavePruductSpuinfoVO spuInfo) {
        //保存spu信息
        //spu_info
        SpuInfoEntity spuInfoEntity = new SpuInfoEntity();
        BeanUtils.copyProperties(spuInfo, spuInfoEntity);
        spuInfoEntity.setCreateTime(LocalDateTime.now());
        spuInfoEntity.setUpdateTime(LocalDateTime.now());
        spuInfoEntity.setPublishStatus(0);//0-新建，1-已上架，2-已下架 默认新建
        save(spuInfoEntity);

        //spu_info_desc
        SpuInfoDescEntity spuInfoDescEntity = new SpuInfoDescEntity();
        spuInfoDescEntity.setSpuId(spuInfoEntity.getId());
        spuInfoDescEntity.setDecript(String.join(",", spuInfo.getDecript()));
        spuInfoDescService.save(spuInfoDescEntity);
        //spu_images
        if(CollectionUtil.isNotEmpty(spuInfo.getImages())){
            List<SpuImagesEntity> spuImagesEntities = new LinkedList<>();
            for (String image : spuInfo.getImages()) {
                SpuImagesEntity spuImagesEntity = new SpuImagesEntity();
                spuImagesEntity.setSpuId(spuInfoEntity.getId());
                spuImagesEntity.setImgUrl(image);
                spuImagesEntities.add(spuImagesEntity);
            }
            spuImagesService.saveBatch(spuImagesEntities);
        }
        //product_attr_value
        List<BaseAttrs> baseAttrs = spuInfo.getBaseAttrs();
        if(CollectionUtil.isNotEmpty(baseAttrs)){
            List<ProductAttrValueEntity> productAttrValueEntities = baseAttrs.stream().map(baseAttr -> {
                ProductAttrValueEntity productAttrValueEntity = new ProductAttrValueEntity();
                productAttrValueEntity.setSpuId(spuInfoEntity.getId());
                productAttrValueEntity.setAttrId(baseAttr.getAttrId());
                AttrEntity attrEntity = attrService.lambdaQuery().select(AttrEntity::getAttrName).eq(AttrEntity::getAttrId, baseAttr.getAttrId()).one();
                if(Objects.nonNull(attrEntity)){
                    productAttrValueEntity.setAttrName(attrEntity.getAttrName());
                }
                productAttrValueEntity.setAttrValue(baseAttr.getAttrValues());
                productAttrValueEntity.setQuickShow(baseAttr.getShowDesc());
                return productAttrValueEntity;
            }).toList();
            productAttrValueService.saveBatch(productAttrValueEntities);
        }
        //保存sku信息
        //sku_info
        List<Skus> skus = spuInfo.getSkus();
        List<SkuInfoEntity> skuInfoEntities=null;
        List<List<Images>> skuImages = new LinkedList<>();
        List<List<Attr>> skuAttrs = new LinkedList<>();
        if(CollectionUtil.isNotEmpty(skus)){
             skuInfoEntities = skus.stream().map(sku -> {
                String skuDefaultImg = null;
                for (Images image : sku.getImages()) {
                    if(image.getDefaultImg() == 1){
                        skuDefaultImg = image.getImgUrl();
                        break;
                    }
                }
                SkuInfoEntity skuInfoEntity = new SkuInfoEntity();
                BeanUtils.copyProperties(sku, skuInfoEntity);
                skuInfoEntity.setSpuId(spuInfoEntity.getId());
                skuInfoEntity.setBrandId(spuInfoEntity.getBrandId());
                skuInfoEntity.setCatalogId(spuInfoEntity.getCatalogId());
                skuInfoEntity.setSaleCount(0L);
                skuInfoEntity.setSkuDefaultImg(skuDefaultImg);
                skuImages.add(sku.getImages());
                skuAttrs.add(sku.getAttr());
                return skuInfoEntity;
            }).toList();
            skuInfoService.saveBatch(skuInfoEntities);
        }
        //sku_images
        if(CollectionUtil.isNotEmpty(skuInfoEntities)){
            for (SkuInfoEntity skuInfoEntity : skuInfoEntities) {
                List<SkuImagesEntity> skuImagesEntities = skuImages.get(skuInfoEntities.indexOf(skuInfoEntity)).stream().map(image -> {
                    SkuImagesEntity skuImagesEntity = new SkuImagesEntity();
                    BeanUtils.copyProperties(image, skuImagesEntity);
                    skuImagesEntity.setSkuId(skuInfoEntity.getSkuId());
                    return skuImagesEntity;
                }).filter(image -> StringUtils.isNotEmpty(image.getImgUrl())).toList();
                skuImagesService.saveBatch(skuImagesEntities);
            }
        }
        //sku_sale_attr_value
        if(CollectionUtil.isNotEmpty(skuInfoEntities)){
            for (SkuInfoEntity skuInfoEntity : skuInfoEntities) {
                List<SkuSaleAttrValueEntity> skuSaleAttrValueEntities = skuAttrs.get(skuInfoEntities.indexOf(skuInfoEntity)).stream().map(attr -> {
                    SkuSaleAttrValueEntity skuSaleAttrValueEntity = new SkuSaleAttrValueEntity();
                    BeanUtils.copyProperties(attr, skuSaleAttrValueEntity);
                    skuSaleAttrValueEntity.setSkuId(skuInfoEntity.getSkuId());
                    return skuSaleAttrValueEntity;
                }).toList();
                skuSaleAttrValueService.saveBatch(skuSaleAttrValueEntities);
            }
        }
        //spu_bounds
        if(Objects.nonNull(spuInfo.getBounds())){
            SpuBoundTO spuBoundTO = new SpuBoundTO();
            BeanUtils.copyProperties(spuInfo.getBounds(), spuBoundTO);
            spuBoundTO.setSpuId(spuInfoEntity.getId());
            couponFeignClient.saveSpuBound(spuBoundTO);
        }
        //远程调用保存sku_ladder, sku_full_reduction, sku_member_price
        if(CollectionUtil.isNotEmpty(skuInfoEntities)){
            for (SkuInfoEntity skuInfoEntity : skuInfoEntities) {
                SkuReductionTO skuReductionTO = new SkuReductionTO();
                Skus sku = skus.get(skuInfoEntities.indexOf(skuInfoEntity));
                if(sku.getFullPrice().compareTo(BigDecimal.ZERO) > 0||sku.getReducePrice().compareTo(BigDecimal.ZERO) > 0){
                    BeanUtils.copyProperties(sku, skuReductionTO);
                    skuReductionTO.setSkuId(skuInfoEntity.getSkuId());
                    couponFeignClient.saveSkuFullReduction(skuReductionTO);
                }
            }
        }
        return R.ok();
    }

    @Override
    public R selectSpuInfo(SelectSpuOrSkuInfoPageRequest selectSpuOrSkuInfoPageRequest) {
        Map<String, Object> params=new HashMap<>();
        params.put("page", selectSpuOrSkuInfoPageRequest.getPage().toString());
        params.put("limit", selectSpuOrSkuInfoPageRequest.getLimit().toString());
        LambdaQueryWrapper<SpuInfoEntity> queryWrapper = new LambdaQueryWrapper<SpuInfoEntity>()
                .eq(Objects.nonNull(selectSpuOrSkuInfoPageRequest.getCatelogId())&& selectSpuOrSkuInfoPageRequest.getCatelogId()>0, SpuInfoEntity::getCatalogId, selectSpuOrSkuInfoPageRequest.getCatelogId())
                .eq(Objects.nonNull(selectSpuOrSkuInfoPageRequest.getBrandId())&& selectSpuOrSkuInfoPageRequest.getBrandId()>0, SpuInfoEntity::getBrandId, selectSpuOrSkuInfoPageRequest.getBrandId())
                .eq(Objects.nonNull(selectSpuOrSkuInfoPageRequest.getStatus()), SpuInfoEntity::getPublishStatus, selectSpuOrSkuInfoPageRequest.getStatus())
                .and(StringUtils.isNotBlank(selectSpuOrSkuInfoPageRequest.getKey()),
                        wrapper -> wrapper.likeLeft(SpuInfoEntity::getSpuName, selectSpuOrSkuInfoPageRequest.getKey())
                                .or().likeLeft(SpuInfoEntity::getSpuDescription, selectSpuOrSkuInfoPageRequest.getKey())
                );

        // 只有当排序字段不为空时才添加排序条件
        if (StringUtils.isNotBlank(selectSpuOrSkuInfoPageRequest.getSidx())) {
            String order = StringUtils.isNotBlank(selectSpuOrSkuInfoPageRequest.getOrder()) ? selectSpuOrSkuInfoPageRequest.getOrder() : "ASC";
            queryWrapper.last("order by " + selectSpuOrSkuInfoPageRequest.getSidx() + " " + order);
        }
        IPage<SpuInfoEntity> page = page(new Query<SpuInfoEntity>().getPage(params), queryWrapper);
        PageUtils pageUtils = new PageUtils(page);
        return R.ok().put("page", pageUtils);
    }

}